package ch.sv7.tool.dbmanager.db.ant;

import org.apache.tools.ant.BuildException;

import ch.sv7.tool.dbmanager.DbManagerException;
import ch.sv7.tool.dbmanager.db.Manager;
import ch.sv7.tool.dbmanager.db.script.ScriptTableWriter;
import ch.sv7.tool.dbmanager.db.sql.SQLFullTableReader;

public class Sql2ScriptTask extends TablesSqlTask {

	public Sql2ScriptTask() {
	}

	public void execute() throws BuildException {
		try {
			java.sql.Connection conn = getConnection();
			try {
				SQLFullTableReader reader = new SQLFullTableReader(conn);
				ScriptTableWriter writer = new ScriptTableWriter(getDirectory(), getSchema(), getFilePattern());
				ch.sv7.tool.dbmanager.db.DatabaseSchema dbSchema = getDatabaseSchema(conn, getTables());
				Manager.copy(reader, writer, dbSchema, getTables());
			} catch (DbManagerException e) {
				throw new BuildException(e, getLocation());
			} catch (Exception e) {
				e.printStackTrace();
				throw new BuildException(e, getLocation());
			} finally {
				closeConnection(conn);
			}
		} catch (DbManagerException e) {
			throw new BuildException(e, getLocation());
		}
	}
}
